package list;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

public class leetcode206 {
    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5};
        ListNode head = createListNode(nums);
        printList(head);
        ListNode tail = null;
//        ListNode result = reverseList(head);
        ListNode result = reverseList_2(head);
        printList(result);
    }

    private static ListNode createListNode(int[] nums){
        ListNode head = new ListNode(nums[0]);
        ListNode current = head;
        for (int i = 1; i < nums.length; i++) {
            ListNode temp = new ListNode(nums[i]);
            current.next = temp;
            current = current.next;
        }
        return head;
    }

    public static ListNode reverseList(ListNode head){
        if(head == null) return null;
        ListNode prev = null;
        ListNode temp = null;
        ListNode cur = head;
        while(cur != null){
            temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }

    public static ListNode reverseList_2(ListNode head){
        if(head == null){
            return null;
        }
        if(head.next == null) {
            return head;
        }
        ListNode cur =  reverseList_2(head.next);
        head.next.next = head;
        head.next = null;
        return cur;
    }
}
